<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ name: 'orders' }">订单管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        {{ isAdd ? '新增订单' : isEdit ? '编辑订单' : '订单详情' }}
      </el-breadcrumb-item>
    </el-breadcrumb>

    <div style="height: 30px"></div>
    <el-form :model="form" :rules="rules" label-width="120px" inline ref="formRef">
      <el-form-item label="客户名称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="请输入" style="width: 200px" />
      </el-form-item>
      <el-form-item label="客户手机" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入" style="width: 200px" />
      </el-form-item>
      <el-form-item label="客户地址" prop="address">
        <el-input
          v-model="form.address"
          placeholder="请输入"
          style="width: 200px"
          type="textarea"
        />
      </el-form-item>
      <el-form-item label="选择商品" prop="goods_id">
        <el-select v-model="form.goods_id" placeholder="请选择" style="width: 200px">
          <el-option
            :label="item.name"
            :value="item.id"
            :key="item.id"
            v-for="item in goodsOptions"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品数量" prop="goods_count">
        <el-input-number v-model="form.goods_count" :min="1" :max="10000" style="width: 200px" />
      </el-form-item>
      <el-form-item label="订单总价" prop="goods_count"> {{ totalPrice }}元 </el-form-item>
      <el-form-item label="预约时间" prop="subscribe_time">
        <el-date-picker
          v-model="form.subscribe_time"
          type="datetime"
          placeholder="请选择预约时间"
          style="width: 200px"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择" style="width: 200px">
          <!-- 1:待付款 2:待上门 3:服务中 4:已完成 5:已取消 -->
          <el-option label="待付款" value="1" />
          <el-option label="待上门" value="2" />
          <el-option label="服务中" value="3" />
          <el-option label="已完成" value="4" />
          <el-option label="已取消" value="5" />
          <el-option label="退款中" value="6" />
          <el-option label="已退款" value="7" />
          <el-option label="退款失败" value="8" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单渠道" prop="channel_id">
        <el-select v-model="form.channel_id" placeholder="请选择" style="width: 200px">
          <el-option
            :label="item.name"
            :value="item.id"
            :key="item.id"
            v-for="item in channelOptions"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品金额" prop="order_price" v-if="false">
        <el-input v-model="form.order_price" style="width: 200px" />
      </el-form-item>
      <el-form-item label="订单备注">
        <el-input v-model="form.remark" placeholder="请输入" style="width: 200px" type="textarea" />
      </el-form-item>
      <el-form-item label="上门师傅">
        <el-select
          v-model="form.worker_name"
          placeholder="请选择上门师傅"
          style="width: 200px"
          @change="changeWork"
          allow-create
          clearable
          filterable
        >
          <el-option
            v-for="item in workList"
            :key="item.id"
            :label="item.work_name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="师傅手机">
        <el-input
          v-model="form.worker_phone"
          autocomplete="off"
          placeholder="请输入师傅手机"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="上门时间">
        <el-date-picker
          v-model="form.work_time"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择上门时间"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="支付凭证??圆形没有" v-if="false">
        <el-input v-model="form.payment_prove" placeholder="请输入" style="width: 200px" />
      </el-form-item>
      <div style="width: 100%; border: 1px solid #f3f3f3; margin: 20px 0"></div>
      <div class="line">
        <el-form-item label="实收金额">
          <el-input v-model="form.real_price" placeholder="请输入" style="width: 200px" />
        </el-form-item>
        <el-form-item label="实收说明">
          <el-input
            v-model="form.payment_desc"
            placeholder="请输入"
            style="width: 200px"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="支付凭证">
          <el-upload
            ref="paymentProveUploadRef"
            list-type="picture-card"
            :limit="1"
            :auto-upload="false"
            accept="image/*"
            :file-list="paymentProveFileList"
            @change="handlePaymentProveChange"
            @remove="handlePaymentProveRemove"
            @preview="handleUploadPreview"
            :show-file-list="true"
            class="payment-prove-upload"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </div>
    </el-form>

    <!-- <el-upload
        @remove="onRemove"
        :file-list="fileList"
        ref="uploadRef"
        list-type="picture-card"
        :limit="1"
        :auto-upload="false"
        accept="image/*"
        @change="handleMainImgChange"
      >
        <el-icon><Plus /></el-icon>
      </el-upload> -->

    <div class="tips">
      <p>
        1.客户转账：将收款码截图微信发给客户，客户发送付款成功微信截图，提交订单
        <br />(待付款），客服通过【编辑】进行订单操作。
        <br />(服务中)，安排上门师傅，必须上传支付凭证。
      </p>
      <p>2.客户小程序付款：提交订单，客户登陆小程序进行付款，客服通过【编辑】进行订单操作。</p>
    </div>

    <div class="actions-btn">
      <el-button type="primary" @click="cancel">关闭</el-button>
      <el-button type="primary" @click="submit" :loading="loading">提交</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { addOrder, editOrder, getOrderInfo, getWorkList } from '@/api/order'
import { getGoodsList } from '@/api/goods'
import { Plus } from '@element-plus/icons-vue'
import { getChannelList } from '@/api/channel'

const channelOptions = ref([])
const workList = ref([])
const route = useRoute()
const router = useRouter()

// 支付凭证相关
const paymentProveFileList = ref([])
const paymentProveUploadRef = ref()
const isAdd = computed(() => route.query.type === '1')
const isEdit = computed(() => route.query.type === '2')

// 计算订单总价
const totalPrice = computed(() => {
  if (!form.value.goods_id || !form.value.goods_count) {
    return 0
  }

  const selectedGoods = goodsOptions.value.find((item) => item.id === form.value.goods_id)
  if (!selectedGoods || !selectedGoods.price) {
    return 0
  }

  return (selectedGoods.price * form.value.goods_count).toFixed(2)
})

const form = ref({
  nickname: '',
  phone: '',
  address: '',
  goods_id: '',
  goods_count: 1,
  remark: '',
  payment_prove: '',
  real_price: '',
  status: '',
  channel_id: '',
  subscribe_time: '',
  payment_desc: '',
  worker_name: '',
  worker_phone: '',
  work_time: '',
})

// 表单校验规则
const rules = {
  nickname: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入客户手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' },
  ],
  address: [{ required: true, message: '请输入客户地址', trigger: 'blur' }],
  goods_id: [{ required: true, message: '请选择商品', trigger: 'change' }],
  goods_count: [
    { required: true, message: '请输入商品数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '商品数量必须大于0', trigger: 'blur' },
  ],
  status: [{ required: true, message: '请选择订单状态', trigger: 'change' }],
  channel_id: [{ required: true, message: '请选择订单渠道', trigger: 'change' }],
  payment_prove: [{ required: true, message: '请上传支付凭证', trigger: 'change' }],
}
// 移除不再需要的 onRemove 方法
const formRef = ref()
const loading = ref(false)

const goodsOptions = ref([])

const cancel = () => {
  router.push({ name: 'orders' })
}

// 师傅选择变化处理
const changeWork = (val) => {
  const item = workList.value.find((item) => item.id === val)
  if (item) {
    form.value.worker_phone = item.work_phone
  }
}

// 支付凭证上传处理
const handlePaymentProveChange = (file) => {
  if (file.raw) {
    form.value.payment_prove = file.raw
  }
}

// 支付凭证删除处理
const handlePaymentProveRemove = (file) => {
  form.value.payment_prove = ''
}

// 图片预览处理
const handleUploadPreview = (file) => {
  if (file.raw) {
    // 如果是新上传的文件，创建本地预览URL
    const url = URL.createObjectURL(file.raw)
    window.open(url)
  } else if (file.url) {
    // 如果是已有的文件，直接打开URL
    window.open(file.url)
  }
}
// 移除不再需要的变量和方法
const submit = async () => {
  if (!formRef.value) return

  try {
    // 表单验证
    await formRef.value.validate()

    loading.value = true

    if (isAdd.value) {
      try {
        const formData = new FormData()
        formData.append('nickname', form.value.nickname)
        formData.append('phone', form.value.phone)
        formData.append('address', form.value.address)
        formData.append('goods_id', form.value.goods_id)
        formData.append('goods_count', form.value.goods_count)
        formData.append('order_price', totalPrice.value)
        formData.append('remark', form.value.remark)
        formData.append('payment_prove', form.value.payment_prove)
        formData.append('channel_id', form.value.channel_id)
        formData.append('status', form.value.status)
        formData.append('subscribe_time', form.value.subscribe_time)
        formData.append('real_price', form.value.real_price)
        formData.append('payment_desc', form.value.payment_desc)
        formData.append('worker_name', form.value.worker_name)
        formData.append('worker_phone', form.value.worker_phone)
        formData.append('work_time', form.value.work_time)
        console.log(formData)
        const res = await addOrder(formData)
        ElMessage.success('新增订单成功')
        router.push({ name: 'orders' })
      } catch (error) {
        console.error('新增订单失败:', error)
        ElMessage.error('新增订单失败')
      }
    } else if (isEdit.value) {
      try {
        await editOrderFun()
      } catch (error) {
        console.error('编辑订单失败:', error)
        ElMessage.error('编辑订单失败')
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请完善必填信息')
  } finally {
    loading.value = false
  }
}

const editOrderFun = async () => {
  const formData2 = new FormData()
  formData2.append('nickname', form.value.nickname)
  formData2.append('phone', form.value.phone)
  formData2.append('address', form.value.address)
  formData2.append('goods_id', form.value.goods_id)
  formData2.append('goods_count', form.value.goods_count)
  formData2.append('order_price', totalPrice.value)
  formData2.append('remark', form.value.remark)
  formData2.append('channel_id', form.value.channel_id)
  formData2.append('status', form.value.status)
  formData2.append('subscribe_time', form.value.subscribe_time)
  formData2.append('real_price', form.value.real_price)
  formData2.append('payment_desc', form.value.payment_desc)
  formData2.append('worker_name', form.value.worker_name)
  formData2.append('worker_phone', form.value.worker_phone)
  formData2.append('work_time', form.value.work_time)
  formData2.append('id', route.query.id)

  // 处理支付凭证
  if (form.value.payment_prove instanceof File) {
    // 如果是新上传的文件
    formData2.append('payment_prove', form.value.payment_prove)
  } else if (typeof form.value.payment_prove === 'string' && form.value.payment_prove) {
    // 如果是已有的URL，去掉/api/前缀
    const url = form.value.payment_prove.startsWith('/api/')
      ? form.value.payment_prove.replace('/api/', '')
      : form.value.payment_prove
    formData2.append('payment_prove', url)
  }
  const res = await editOrder(formData2)
  ElMessage.success('编辑订单成功')
  router.push({ name: 'orders' })
}

// 移除不再需要的 fileList
onMounted(async () => {
  const res = await getGoodsList({
    page: 1,
    page_size: 1000,
    status: 1,
  })
  const res2 = await getChannelList({
    page: 1,
    page_size: 1000,
    status: 1,
  })
  const res3 = await getWorkList()
  channelOptions.value = res2.data.list
  goodsOptions.value = res.data.list
  workList.value = res3.data.list
  if (isEdit.value) {
    const res = await getOrderInfo(route.query.id)
    form.value.nickname = res.data.customer_name
    form.value.phone = res.data?.customer_mobile
    form.value.address = res.data.address
    form.value.goods_id = res.data.goods_id
    form.value.goods_count = res.data.goods_count
    form.value.payment_prove = res.data.payment_prove
    form.value.remark = res.data.remark
    form.value.channel_id = res.data.channel_id
    form.value.status = res.data.status + ''
    form.value.subscribe_time = res.data.subscribe_time
    form.value.real_price = res.data.real_price
    form.value.payment_desc = res.data.payment_desc
    form.value.worker_name = res.data.worker_name || ''
    form.value.worker_phone = res.data.worker_phone || ''
    form.value.work_time = res.data.work_time || ''

    // 处理支付凭证回显
    if (res.data.payment_prove) {
      form.value.payment_prove = res.data.payment_prove
      paymentProveFileList.value = [
        {
          name: 'payment_prove.png',
          url: `/api/${res.data.payment_prove}`,
          status: 'success',
        },
      ]
    }
  }
})
</script>

<style scoped lang="scss">
.actions-btn {
  margin-top: 20px;
  text-align: center;
}

.img-2 {
  width: 150px !important;
  height: 150px !important;
  overflow: hidden;
  margin-bottom: 20px;
  margin-left: 40px;
}

/* 隐藏支付凭证上传组件的 Plus 按钮（当有文件时） */
.payment-prove-upload
  :deep(.el-upload-list--picture-card .el-upload-list__item + .el-upload--picture-card) {
  display: none !important;
}
</style>
